package marchenko.springdao.repository.book;

import java.util.List;

import marchenko.springdao.domain.Book;
import marchenko.springdao.domain.BookClass;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

public class BookRepositoryImpl implements BookRepository {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	private final static String SELECT_ALL = "select b.id, bc.id as class_id, bc.name as class_name, "
			+ "a.id as author_id, a.name as author_name, "
			+ "g.id as genre_id, g.name as genre_name, bc.description "
			+ "from books b "
			+ "left join book_classes bc on b.class_id=bc.id "
			+ "left join authors a on a.id=bc.author_id "
			+ "left join genres g on g.id=bc.genre_id ";
	
	public Book find(Integer id) throws DataAccessException {
		return jdbcTemplate.queryForObject(SELECT_ALL+"where b.id = ?",
				new BookMapper(), id);
	}

	public List<Book> findByClass(BookClass bclass) throws DataAccessException {
		return jdbcTemplate.query(
				SELECT_ALL+"where class_id = ?", new BookMapper(), bclass.getClassId());
	}

	public List<Book> findAll() throws DataAccessException {
		return jdbcTemplate.query(SELECT_ALL, new BookMapper());
	}

	public boolean create(Book newinstance) throws DataAccessException {
		return jdbcTemplate.update("insert into books (id,class_id) values (?,?)",
				newinstance.getBookId(),
				newinstance.getBclass().getClassId()) > 0;
	}

	public boolean deleteById(Integer id) throws DataAccessException {
		return jdbcTemplate.update("delete from books where id = ?", id) > 0;
	}
}
